<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content">
        <div class="login-header">
          <h2 class="login-brand">毕业设计过程管理系统</h2>
        </div>
        <div class="login-body">
          <el-form 
            :model="loginForm" :rules="loginRules" ref="loginForm" v-loading="loading" 
            element-loading-text="正在登录..."
            element-loading-spinner="el-icon-loading" 
            status-icon
            
             @keydown.enter.native.prevent="submitLogin()"
            >
            <!-- element-loading-background="rgba(0.5, 0.5, 0.5, 0.7)" -->
            <h3 class="login-title">用户登录</h3>
            <el-form-item size="mini">
              <el-radio-group v-model="loginMethod">
                <el-radio-button :label="0">用户名登录</el-radio-button>
                <el-radio-button :label="1">手机号登录</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <div v-if="loginMethod == 0">
              <el-form-item prop="username" >
                <!-- :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]" -->
                <el-input size="normal" type="text" v-model="loginForm.username" auto-complete="off" placeholder="请输入用户名">
                  <i slot="prefix" class="el-icon-user"></i>
                </el-input>
              </el-form-item>
          
              <el-form-item prop="password" >
                <!-- :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]" -->
                <el-input size="normal" show-password v-model="loginForm.password" auto-complete="off" placeholder="请输入密码">
                  <i slot="prefix" class="el-icon-lock">
                  </i>
                </el-input>
              </el-form-item>
          
              <el-form-item prop="captcha">
                <el-row :gutter="9">
                  <el-col :span="14">
                    <el-input v-model="loginForm.captcha" placeholder="点击图片更换验证码">
                      <span slot="prefix" class="el-input__icon">
                        <svg class="icon-svg" aria-hidden="true">
                          <use xlink:href="#icon-safetycertificate"></use>
                        </svg>
                      </span>
                    </el-input>
                  </el-col>
                  <el-col :span="10" class="login-captcha">
                    <!-- <img :src="captchaPath" @click="getCaptcha()"> -->
                    <el-tooltip effect="dark" content="点击图片更换验证码" placement="top">
                      <div @click="updateVerifyCode"  class="cursor captcha">
                        <verify-code :identifyCode="identifyCode"></verify-code>
                      </div>
                    </el-tooltip>
                  </el-col>
                </el-row>
                <!-- <el-input size="normal" type="text" v-model="loginForm.captcha" auto-complete="off" placeholder="点击图片更换验证码"
                  @keydown.enter.native="submitLogin" style="width: 250px"></el-input> -->
                <!-- @keydown.enter.native 回车键登录 -->
                <!-- <img :src="vcUrl" @click="updateVerifyCode" alt="验证码" style="cursor: pointer"> -->
                <!-- <el-tooltip effect="dark" content="点击图片更换验证码" placement="top">
                  <div @click="updateVerifyCode" class="cursor captcha">
                    <VerifyCode :identifyCode="identifyCode">
                    </VerifyCode>
                  </div>
                </el-tooltip> -->
          
              </el-form-item>
              <el-form-item>
                <el-switch v-model="rmbPwd" style="width: 78%;" active-text="记住密码" @change="rememberPwd"></el-switch>
                <el-link :underline="false" href="/forget-password" @click="forgetPwd('')">忘记密码</el-link>
              </el-form-item>
            </div>
            <div v-if="loginMethod == 1">
              <el-form-item prop="phone">
                <el-input size='normal' type="text" v-model="loginForm.phone" auto-complete="off" placeholder="请输入手机号">
                  <i slot="prefix" class="el-icon-phone"></i>
                </el-input>
              </el-form-item>
          
              <el-form-item prop="code">
                <el-input size="normal" v-model="loginForm.code" auto-complete="off" placeholder="请输入短信验证码">
                  <i slot="prefix" class="el-icon-message"> </i>
                  <el-button slot="suffix" @click="getPhoneMsg" type="primary" :disabled="canClick" class="sendBtn">
                    {{ btnText }}
                  </el-button>
                </el-input>
              </el-form-item>
          
            </div>
            
          
          
            <el-button size="normal" type="primary" style="width: 100%;" @click="submitLogin">登录</el-button>
          </el-form>
        </div>
        
      </main>
    </div>
  </div>
</template>

<script >
import servicesApi from '@/services/servicesApi'
import VerifyCode from '@/components/VerifyCode.vue'
import { makeCaptcha } from '@/utils/captcha'
import storageService from '@/store/storage'
import { debounce } from 'lodash'//引入防抖
import { rsaCrypto } from '@/utils/crypto'
import JSEncrypt from '@/utils/jsencrypt.min.js'
import { PUBLICKEY } from '@/store/storage'
import { isMobile } from '@/utils/validate'
export default {
  name: 'login',
  components: {
    VerifyCode
  },
  data() {
    return {
      rmbPwd: false, //记住密码
      loading: false,
      identifyCode: '',
      loginMethod: 0,
      btnText: '发送验证码',
      totalTime: 30,
      canClick: false,
      loginForm: {
        username: '',
        password: '',
        captcha: '',
        phone: '15583772258', // 13982677074
        code: '',
      },
    }
  },
  watch: {
    loginMethod(val) { // 函数名是要监听的属性
      // 重置表单，清空校验信息
      // console.log('监听的值=%s', val)
      this.$nextTick(() => {
        //  延时到下一帧才开始，也就是页面刚刚渲染结束！！
        this.$refs.loginForm.clearValidate()
      })
    }
  },
  computed: {
    loginRules() {
      let validateCaptcha = (rule, value, callback) => {
        if (value !== this.identifyCode) {
          callback(new Error('请输入正确的验证码'));
        } else {
          callback();
        }
      }
      let validatePhone = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('请输入正确的手机号码'));
        } else {
          callback();
        }
      }
      return {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: validatePhone, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }, { validator: validateCaptcha, trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      }
    }
  },
  
  created() { //在模板渲染成html前调用,通常用于初始化某些属性值
    // 验证码初始化
    this.updateVerifyCode()
    //加载cookie
    this.uploadCookie()
    // this.getPublicKey()
    // console.log(process.env.NODE_ENV)
    // console.log(window.SITE_CONFIG['apiURL'])
  },
  mounted() { //在模板渲染成html后调用,通常在初始化页面完成后，对html的dom节点进行需要的操作。
    // this.getPublicKey()
  },
  activated() { //每次进入页面都会执行
    // this.getPublicKey()
  },
  methods: {
    getPhoneMsg() {
      this.loading = true
      servicesApi.getCode(this.loginForm.phone).then(res => {
        if (this.canClick) return
        this.canClick = true
        this.btnText = this.totalTime + 's后重新发送'
        let clock = window.setInterval(() => {
          this.totalTime--
          this.btnText = this.totalTime + 's后重新发送'
          if (this.totalTime < 0) {
            window.clearInterval(clock)
            this.btnText = '重新发送验证码'
            this.totalTime = 30
            this.canClick = false
          }
        }, 1000)
        let code = res.data.code
        if (code===200) {
          this.$message.success('短信发送成功，请注意查看');
        } else {
          this.$message.error('短信发送失败，请稍后重试');
        }
        // // console.log('公钥为：%s', data)
        // sessionStorage.setItem(PUBLICKEY, data) //公钥存入session
      })
      this.loading = false
    },
    async getPublicKey() {
      await servicesApi.getRsaPublicKey().then(res => {
        let data = res.data.data
        // // console.log('公钥为：%s', data)
        sessionStorage.setItem(PUBLICKEY, data) //公钥存入session
      })
    },
    forgetPwd(username) { //路由传参
      // 1、传参可以使用params和query两种方式。
      // 2、使用params传参只能用name来引入路由，即push里面只能是name:’xxxx’, 不能是path:’/xxx’,因为params只能用name来引入路由，如果这里写成了path，接收参数页面会是undefined！！！。
      // 3、使用query传参使用path来引入路由。
      // 4、params是路由的一部分, 必须要在路由后面添加参数名。query是拼接在url后面的参数，没有也没关系。
      // 5、二者还有点区别，直白的来说query相当于get请求，页面跳转的时候，可以在地址栏看到请求参数，而params相当于post请求，参数不会再地址栏中显示。
      // this.$router.push({ name: 'forget-password', params: { account: username } })
    },
    uploadCookie() {// 在页面加载时从cookie获取登录信息
      let obj= storageService.getRmbPwd()//获取解密后的对象
      if (obj != null) {
        this.rmbPwd = true
        this.loginForm.password = obj.password
        this.loginForm.username = obj.username
      }
    },
    //记住密码
    rememberPwd() {
      // console.log(this.rmbPwd);
      // this.rmbPwd= !this.rmbPwd //cahnge函数自动改变其值
      const form= this.loginForm
      // console.log('点击记住密码');
      if (this.rmbPwd) {
        if (form.password!=''&&form.username!='') {
          storageService.setRmbPwd(form);
          // console.log('存入cookie');
        } else {
          // alert('用户名/密码为空')
          this.$message.error('记住密码时用户名和密码空不能为空')
          this.rmbPwd=false
        }
      } else {
        storageService.removeRmbPwd()
      }
    },
    // 切换验证码
    updateVerifyCode() {
      this.identifyCode = makeCaptcha()
      // this.loginForm.captcha = ''
      this.loginForm.captcha = this.identifyCode 
    },
    // 表单提交
    submitLogin: debounce(function() { 
      this.$refs['loginForm'].validate((valid) => {
        if (!valid) { return false }
        this.loading = true
        this.getPublicKey().then(() => {
          if (this.loginMethod == 1) {
            // console.log('手机号登录')
            let phoneForm = {
              phone: this.loginForm.phone,
              code: this.loginForm.code,
              model: '',
            }
            servicesApi.phoneLogin(phoneForm).then(res => {
              this.loading = false
              let code = res.data.code
              let msg = res.data.msg
              if (code === 200) { //鉴权成功
                let Token = res.data.data.csrfToken;
                let userId = res.data.data.userId;
                //存入userId
                storageService.setAccountId(userId)
                // console.log('登录用户的id=%s', userId)
                //存入token
                // console.log('token=%s', Token)
                storageService.setToken(Token)
                //注意如果设置了路由守卫，要先存token再跳转页面，顺序一定不能反
                // this.rememberPwd();
                this.$router.replace({ name: 'home', params: { hasLogin: true } })
              } else if (code === 201) {
                let Token = res.data.data.csrfToken;
                let userId = res.data.data.userId;
                //存入userId
                storageService.setAccountId(userId)
                // console.log('首次登录用户的id=%s', userId)
                //存入token
                // console.log('token=%s', Token)
                storageService.setToken(Token)
                this.$router.replace({ name: 'home', params: { hasLogin: false } })
                // this.forgetPwd(this.loginForm.username)
              } else {
                return this.$message.error(msg)
              }
            })
          } else {
            // this.rememberPwd()

            // var encryptor = new JSEncrypt();
            // let pk = sessionStorage.getItem(PUBLICKEY)
            // // // console.log('pk=%s',pk)
            // encryptor.setPublicKey(pk);
            // let encodePwd = encryptor.encrypt(this.loginForm.password);
            // // console.log('min.js加密后->%s', encodePwd);

            let encodePwd1 = rsaCrypto(this.loginForm.password);
            // // console.log('封装加密后->%s', encodePwd1);
            // this.loginForm.password = enPwd

            let Form = {
              username: this.loginForm.username,
              password: encodePwd1, // encodePwd  this.loginForm.password
              captcha: this.loginForm.captcha
            }
            servicesApi.login(Form).then(res => {
              this.loading = false
              this.rememberPwd()
              // // console.log(res);
              let code = res.data.code
              let msg = res.data.msg
              if (code === 200) { //鉴权成功
                let Token = res.data.data.csrfToken;
                let userId = res.data.data.userId;
                //存入userId
                storageService.setAccountId(userId)
                // console.log('登录用户的id=%s', userId)
                //存入token
                // console.log('token=%s', Token)
                storageService.setToken(Token)
                //注意如果设置了路由守卫，要先存token再跳转页面，顺序一定不能反
                // this.rememberPwd();
                this.$router.replace({ name: 'home', params: { hasLogin: true } })
              } else if (code === 201) {
                let Token = res.data.data.csrfToken;
                let userId = res.data.data.userId;
                //存入userId
                storageService.setAccountId(userId)
                // console.log('登录用户的id=%s', userId)
                //存入token
                // console.log('token=%s', Token)
                storageService.setToken(Token)
                // this.forgetPwd(this.loginForm.username)
                this.$router.replace({ name: 'home', params: { hasLogin: false } })
              } else {
                this.updateVerifyCode()
                return this.$message.error(msg)
              }
            })
          }
        })
        

      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style scoped>
.sendBtn {
  border-radius: 50px;
  width: fit-content;
}
.method{
  width: 100px;
}
.captcha{
  margin-left: 20px;
  text-align: center;
}
.cursor{
  cursor: pointer;
}
.sysName{
  color: whitesmoke;
  text-align:center;
}
.sysName1 {
  text-align: center;
}
.loginContainer {
  border-radius: 15px;
  background-clip: padding-box;
  margin: 10px auto;
  width: 350px;
  padding: 15px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}

.loginTitle {
  margin: 15px auto 20px auto;
  text-align: center;
  color: #505458;
}

.loginRemember {
  text-align: left;
  margin: 0px 0px 15px 0px;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}
.userLogo{
  /* background: red; */
  width: 32px;
  height: 32px;
}
</style>
